from datetime import datetime
# from wsgiref.handlers import format_date_time
import datetime
from time import mktime, time
import hashlib
import base64
import hmac
from urllib.parse import urlencode
import os
import traceback
import json
import requests
from pywinauto.timings import timestamp


class AssembleHeaderException(Exception):
    def __init__(self, msg):
        self.message = msg


class Url:
    def __init__(this, host, path, schema):
        this.host = host
        this.path = path
        this.schema = schema
        pass


# calculate sha256 and encode to base64
def sha256base64(data):
    sha256 = hashlib.sha256()
    sha256.update(data)
    digest = base64.b64encode(sha256.digest()).decode(encoding='utf-8')
    return digest


def parse_url(requset_url):
    stidx = requset_url.index("://")
    host = requset_url[stidx + 3:]
    schema = requset_url[:stidx + 3]
    edidx = host.index("/")
    if edidx <= 0:
        raise AssembleHeaderException("invalid request url:" + requset_url)
    path = host[edidx:]
    host = host[:edidx]
    u = Url(host, path, schema)
    return u


# build websocket auth request url
def assemble_ws_auth_url(requset_url, method="POST", api_key="", api_secret=""):
    u = parse_url(requset_url)
    host = u.host
    path = u.path
    # now = datetime.now()
    # date = format_date_time(mktime(now.timetuple()))
    # print(date)
    # date = "Thu, 12 Dec 2019 01:57:27 GMT"
    date = datetime.datetime.now(datetime.timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT')
    signature_origin = "host: {}\ndate: {}\n{} {} HTTP/1.1".format(host, date, method, path)
    # print(signature_origin)
    signature_sha = hmac.new(api_secret.encode('utf-8'), signature_origin.encode('utf-8'),
                             digestmod=hashlib.sha256).digest()
    signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')
    authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
        api_key, "hmac-sha256", "host date request-line", signature_sha)
    authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
    # print(authorization_origin)
    values = {
        "host": host,
        "date": date,
        "authorization": authorization
    }

    return requset_url + "?" + urlencode(values)


def invoice_util(path):
    APIKey = "3ad055e0de46fa9ebf5afe0df94225a8"
    APPId = "31081998"
    APISecret = "M2MwYjcxMzEwOWVhNjA3MzNiN2U5ZDhl"
    # path = "D://test.png"
    w = open(path, 'rb')
    t = base64.b64encode(w.read())

    # url = 'https://iflydigita.api.xf-yun.com/v1/private/se9b136aa'
    url = 'http://iflydigita.api.xf-yun.com/v1/private/se9b136aa'

    body = {
        "header": {
            "app_id": APPId,
            "uid": "3976979589",
            "did": "SR08232194000020",
            "imei": "866402031869366",
            "imsi": "460026495272910",
            "mac": "6c:92:bf:65:c6:14",
            "net_type": "wifi",
            "net_isp": "CMCC",
            "status": 3,
            "request_id": ""
        },
        "parameter": {
            "se9b136aa": {
                "result": {
                    "encoding": "utf8",
                    "compress": "raw",
                    "format": "json"
                }
            }
        },
        "payload": {
            "default_request_data_1": {
                "encoding": "png",
                "image": str(t, 'UTF-8'),
                "status": 3
            }
        }
    }

    request_url = assemble_ws_auth_url(url, "POST", APIKey, APISecret)

    headers = {'content-type': "application/json", 'host': 'api.xf-yun.com', 'app_id': APPId}
    # print(request_url)
    # print(json.dumps(body))
    response = requests.post(request_url, data=json.dumps(body), headers=headers)
    # print(response.json())
    st = response.json().get('payload').get('result').get('text')
    result = base64.b64decode(st).decode('utf-8')
    # print(result)
    # print(json.dumps(result,ensure_ascii=False))
    result = json.loads(result).get('response').get('data').get('identify_results')[0].get('details')
    # print(result)
    w.close()
    return result


if __name__ == "__main__":
    # APIKey = "3ad055e0de46fa9ebf5afe0df94225a8"
    # APPId = "31081998"
    # APISecret = "M2MwYjcxMzEwOWVhNjA3MzNiN2U5ZDhl"
    # path = "D://test.png"
    # w = open(path, 'rb')
    # t = base64.b64encode(w.read())
    #
    # # url = 'https://iflydigita.api.xf-yun.com/v1/private/se9b136aa'
    # url = 'http://iflydigita.api.xf-yun.com/v1/private/se9b136aa'
    #
    # body = {
    #     "header": {
    #         "app_id": APPId,
    #         "uid": "3976979589",
    #         "did": "SR08232194000020",
    #         "imei": "866402031869366",
    #         "imsi": "460026495272910",
    #         "mac": "6c:92:bf:65:c6:14",
    #         "net_type": "wifi",
    #         "net_isp": "CMCC",
    #         "status": 3,
    #         "request_id": ""
    #     },
    #     "parameter": {
    #         "se9b136aa": {
    #             "result": {
    #                 "encoding": "utf8",
    #                 "compress": "raw",
    #                 "format": "json"
    #             }
    #         }
    #     },
    #     "payload": {
    #         "default_request_data_1": {
    #             "encoding": "png",
    #             "image": str(t,'UTF-8'),
    #             "status": 3
    #         }
    #     }
    # }
    #
    # request_url = assemble_ws_auth_url(url, "POST", APIKey, APISecret)
    #
    # headers = {'content-type': "application/json", 'host': 'api.xf-yun.com', 'app_id': APPId}
    # # print(request_url)
    # # print(json.dumps(body))
    # response = requests.post(request_url, data=json.dumps(body), headers=headers)
    # # print(response)
    # st = response.json().get('payload').get('result').get('text')
    # result = base64.b64decode(st).decode('utf-8')
    # # print(json.dumps(result,ensure_ascii=False))
    # print(json.loads(result).get('response').get('data').get('identify_results')[0].get('details').get('code'))
    # w.close()

    # path = "D://test//IMG_20211216_172610.jpg"
    # s = invoice_util(path)
    # print(s)

    s = ['52307630', '2021-12-11']
    print(s[0])

    # Wed, 18 May 2022 09:06:59 GMT
    # print(datetime.datetime.now())
    # print(datetime.utcnow().timestamp() * 1000)

    # print(datetime.datetime.now(datetime.timezone.utc).strftime('%a, %d %b %Y %H:%M:%S GMT'))



    # s = "发票存在问题微信图片_20220516163531.jpg"
    # identify = ["查无此票", "已抵扣", "发票存在问题"]
    # t = False
    # for i in range(len(identify)):
    #     print(identify[i])
    #     if (identify[i] in s):
    #         t = True
    # print(t)
